package com.doform.android.xianggucheng.activity.downorder;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.activity.BaseTitleActivity;
import com.doform.android.xianggucheng.bean.CategoryQueryBean;
import com.doform.android.xianggucheng.bean.Goods;
import com.doform.android.xianggucheng.bean.GuidBean;
import com.doform.android.xianggucheng.bean.ShopCarBean;
import com.doform.android.xianggucheng.bean.StarBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqListArticleBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqListStarBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqQueryCategory;
import com.doform.android.xianggucheng.popwindow.CommonPopWindow;
import com.doform.android.xianggucheng.retrofit.ApiSpecTransformer.ApiSpecTransformerArticleDown;
import com.doform.android.xianggucheng.retrofit.ApiSpecTransformer.DialogTransformer;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.TsUtils;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

import static com.doform.android.xianggucheng.R.id.iv_shop_car;

/**
 * Created by Administrator on 2017/5/10.
 * 其实就是从仓库调货物发出去的一个功能
 */

public class ManGoodsActivity extends BaseTitleActivity implements OnLoadmoreListener, OnRefreshListener {

    @BindView(R.id.tv_shop_car_num)
    TextView mShopCarNum;

    @BindView(R.id.tv_empty)
    TextView tv_empty;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(iv_shop_car)
    TextView mShopCar;

    @BindView(R.id.tv_category)
    TextView mCategory;

    @BindView(R.id.ll)
    RelativeLayout mLl;

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    @BindView(R.id.rl2)
    LinearLayout mrl2;

    @BindView(R.id.et_query)
    EditText et_query;

    @BindView(R.id.btn_query)
    Button btn_query;


    private TextView mPopTitle;
    private int shopCarNum = 0;
    private TextView mStarTitle;
    private RecyclerView mPopRecycler;
    private RecyclerView mStarRecycler;
    private CommonAdapter mCommonAdapter;
    private CommonPopWindow mPopCategory, mPopStar;
    private List<Goods.ListBean> mDatas = new ArrayList<>();
    private CommonAdapter<StarBean.ListBean> mStarCommonAdapter;
    private List<StarBean.ListBean> mStarDatas = new ArrayList<>();
    private List<CategoryQueryBean> mCategoryDatas = new ArrayList<>();

    public static final int PAGE_CONTENT_INIT = 1;
    private int mCurrentPage = PAGE_CONTENT_INIT;
    private CommonAdapter mCommonCategoryAdater;

    @Override
    protected int layoutResId() {
        return R.layout.activity_man_goods;
    }

    @Override
    protected void init() {
        super.init();
        if (mPopCategory == null) {
            mPopCategory = new CommonPopWindow(this, R.layout.pop_recycler_item);
        }

        if (mPopStar == null) {
            mPopStar = new CommonPopWindow(this, R.layout.pop_recycler_item);
        }
    }


    @Override
    protected void initView() {
//      星级Pop
//        mStarTitle = mPopCategory.getView(R.id.tv_title);
//        mStarRecycler = mPopCategory.getView(R.id.recyclerView);
//
//        mStarRecycler.setLayoutManager(new LinearLayoutManager(this));
//        mStarRecycler.setItemAnimator(new DefaultItemAnimator());
//        mStarRecycler.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

//      分类Pop
        mPopTitle = mPopCategory.getView(R.id.tv_title);
        mPopRecycler = mPopCategory.getView(R.id.recyclerView);
        mPopRecycler.setLayoutManager(new LinearLayoutManager(this));
        mPopRecycler.setItemAnimator(new DefaultItemAnimator());
        mPopRecycler.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    }

    @Override
    protected void initData() {
        super.initData();
        getStarData();
        getCategoryData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        getShopCar();
        refresh();
    }

    private void refresh() {
        mCurrentPage = PAGE_CONTENT_INIT;
        getDataForService(mCurrentPage);
    }

    private void getStarData() {
        HttpManager.instance()
                .getStar2(new ReqListStarBean("1"))
                .subscribe(new ErrorHandleSubscriber<StarBean>() {
                    @Override
                    public void onNext(@NonNull StarBean starBean) {
                        mStarDatas.addAll(starBean.getList());
                        mStarCommonAdapter.notifyDataSetChanged();
                    }
                });
    }

    @Override
    protected void showView() {
        titleBar.setTextTitle("商品");
//        titleBar.setRightText("星级价格");
        mPopTitle.setText("全部");
    }

    @Override
    protected void initListener() {

        refreshLayout.setEnableHeaderTranslationContent(false);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadmoreListener(this);

        initGoodsAdapter();
        initCategoryAdapter();

//        mStarCommonAdapter = new CommonAdapter<StarBean.ListBean>(this, R.layout.pop_item, mStarDatas) {
//            @Override
//            protected void convert(ViewHolder holder, StarBean.ListBean bean, int position) {
//                TextView tv = holder.getView(R.id.tv);
//                tv.setText(bean.getName());
//            }
//        };
//
//        mStarCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
//
//            }
//
//            @Override
//            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
//                return false;
//            }
//        });

//        mStarRecycler.setAdapter(mStarCommonAdapter);

        titleBar.setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopStar.showAsDropDown(titleBar);
            }
        });
    }

    private void initCategoryAdapter() {

        mCommonCategoryAdater = new CommonAdapter<CategoryQueryBean>(this, R.layout.pop_category_item2, mCategoryDatas) {
            @Override
            protected void convert(ViewHolder holder, CategoryQueryBean listBean, int position) {
                TextView tv_name = holder.getView(R.id.tv);
                TextView tv_name2 = holder.getView(R.id.tv2);
                if (listBean.getLv() == 2) {//二级
                    tv_name2.setText(listBean.getName());
                } else if (listBean.getLv() == 1) {
                    tv_name.setText(listBean.getName());
                } else {
                }
            }
        };


        mCommonCategoryAdater.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

                String mCategoryId = mCategoryDatas.get(position).getId();
                mCurrentPage = PAGE_CONTENT_INIT;
                getDataForService3(mCurrentPage,"", mCategoryId);
                mPopCategory.dismiss();

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mPopRecycler.setAdapter(mCommonCategoryAdater);

    }

    //    获取购物车数据
    private void getShopCar() {
        HttpManager.instance()
                .getShopCarData("1")
                .subscribe(new ErrorHandleSubscriber<ShopCarBean>() {
                    @Override
                    public void onNext(@NonNull ShopCarBean shopCarBean) {
                        parseShopCarData(shopCarBean.getNum());
                    }
                });
    }

    private void parseShopCarData(int num) {
        shopCarNum = num;
        mShopCarNum.setText(shopCarNum + "");
        if (0 != shopCarNum) {
            mShopCar.setSelected(true);
        } else {
            mShopCar.setSelected(false);
        }
    }


    private void getDataForService(int pageid) {
        getDataForService(pageid, "");
    }

    /**
     * @param pageId
     */
    private void getDataForService(int pageId, String key) {
        HttpManager.instance()
                .getArticle2(new ReqListArticleBean(String.valueOf(pageId), key,"1"))
                .compose(new ApiSpecTransformerArticleDown<Goods>())
                .compose(new DialogTransformer<Goods>(mProgressBar))
                .subscribe(new ErrorHandleSubscriber<Goods>() {
                    @Override
                    public void onNext(@NonNull Goods goods) {
                        parseData(goods.getList());
                    }
                });
    }

    /**
     * 分类查找
     *
     * @param pageId
     */
    private void getDataForService3(int pageId, String key,String categoryId) {
        HttpManager.instance()
                .getArticle2(new ReqListArticleBean(String.valueOf(pageId), key,categoryId,"1"))
//                .compose(new ApiSpecTransformerArticleDown<Goods>())
                .compose(new DialogTransformer<Goods>(mProgressBar))
                .subscribe(new ErrorHandleSubscriber<Goods>() {
                    @Override
                    public void onNext(@NonNull Goods goods) {
                        parseData(goods.getList());
                    }
                });
    }

    private void getDataForService2(int pageid) {
        getDataForService2(pageid, "");
    }

    /**
     * @param pageId
     */
    private void getDataForService2(int pageId, String key) {
        HttpManager.instance()
                .getArticle2(new ReqListArticleBean(String.valueOf(pageId), key))
                .compose(new ApiSpecTransformerArticleDown<Goods>())
                .subscribe(new ErrorHandleSubscriber<Goods>() {
                    @Override
                    public void onNext(@NonNull Goods goods) {
                        parseData(goods.getList());
                    }
                });
    }


    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mCurrentPage = PAGE_CONTENT_INIT;
        getDataForService2(mCurrentPage);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mCurrentPage++;
        getDataForService2(mCurrentPage);
    }


    private void parseData(List<Goods.ListBean> data) {
        if (mCurrentPage == PAGE_CONTENT_INIT) {
            mDatas.clear();
        }

        if (data.size() == 0 || data == null) {
            mCurrentPage--;
            refreshLayout.finishLoadmore();
            return;
        }
        mDatas.addAll(data);
        mCommonAdapter.notifyDataSetChanged();
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
    }

    private void getCategoryData() {
        HttpManager.instance()
                .getCategoryQuery2(new ReqQueryCategory())
                .subscribe(new ErrorHandleSubscriber<ArrayList<CategoryQueryBean>>() {
                    @Override
                    public void onNext(@NonNull ArrayList<CategoryQueryBean> categoryBean) {
                        notifyData(categoryBean);
                    }
                });
    }

    //    填充Popwindow数据
    private void notifyData(List<CategoryQueryBean> data) {
        mCategoryDatas.addAll(data);
        if (mCommonCategoryAdater != null) {
            mCommonCategoryAdater.notifyDataSetChanged();
        }
    }

    private void initGoodsAdapter() {

        mCommonAdapter = new CommonAdapter<Goods.ListBean>(this, R.layout.activity_man_goods_item, mDatas) {
            @Override
            protected void convert(ViewHolder holder, Goods.ListBean goods, int position) {
                final TextView mName = holder.getView(R.id.tv_name);
                TextView mWeight = holder.getView(R.id.tv_weight);
                TextView mPrice = holder.getView(R.id.tv_price);

                mName.setText(goods.getName());
                mWeight.setText(goods.getSpecification());
                mPrice.setText("￥" + goods.getCostprice() + "/" + goods.getUnit());

            }
        };
        mCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Goods.ListBean dataBean = mDatas.get(position);
                postShopCar(dataBean, view);//添加购物车
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mRecyclerView.setAdapter(mCommonAdapter);
    }

    private void addShopCarAnimation(View location, final int shopCarNum) {

        final ImageView goods = new ImageView(this);
        goods.setImageResource(R.drawable.circle_shape);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        mLl.addView(goods, params);

        int[] parentLocation = new int[2];
        mLl.getLocationInWindow(parentLocation);

        int startLoc[] = new int[2];
        location.getLocationInWindow(startLoc);

        int endLoc[] = new int[2];
        mShopCar.getLocationInWindow(endLoc);

        float startX = startLoc[0] - parentLocation[0] + location.getWidth() / 2;
        float startY = startLoc[1] - parentLocation[1] + location.getHeight() / 2;

        float toX = endLoc[0] - parentLocation[0] + mShopCar.getWidth() / 5;
        float toY = endLoc[1] - parentLocation[1];

        Path path = new Path();
        path.moveTo(startX, startY);
        // 使用二阶贝塞尔曲线：注意第一个起始坐标越大，贝塞尔曲线的横向距离就会越大，一般按照下面的式子取即可
        path.quadTo((startX + toX) / 2, startY, toX, toY);
        // mPathMeasure用来计算贝塞尔曲线的曲线长度和贝塞尔曲线中间插值的坐标，如果是true，path会形成一个闭环
        mPathMeasure = new PathMeasure(path, false);

        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
        valueAnimator.setDuration(500);

        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 当插值计算进行时，获取中间的每个值，
                // 这里这个值是中间过程中的曲线长度（下面根据这个值来得出中间点的坐标值）
                float value = (Float) animation.getAnimatedValue();
                // 获取当前点坐标封装到mCurrentPosition
                // boolean getPosTan(float distance, float[] pos, float[] tan) ：
                // 传入一个距离distance(0<=distance<=getLength())，然后会计算当前距离的坐标点和切线，pos会自动填充上坐标，这个方法很重要。
                // mCurrentPosition此时就是中间距离点的坐标值
                mPathMeasure.getPosTan(value, mCurrentPosition, null);
                // 移动的商品图片（动画图片）的坐标设置为该中间点的坐标
                goods.setTranslationX(mCurrentPosition[0]);
                goods.setTranslationY(mCurrentPosition[1]);
            }
        });

        // 开始执行动画
        valueAnimator.start();

        // 动画结束后的处理
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                // 购物车商品数量加1
                parseShopCarData(shopCarNum);
//                    isShowCartGoodsCount();
//                    mShoppingCartCountTv.setText(String.valueOf(goodsCount));
//                     把执行动画的商品图片从父布局中移除
                mLl.removeView(goods);
            }
        });
    }

    // 路径测量
    private PathMeasure mPathMeasure;
    // 贝塞尔曲线中间过程点坐标
    private float[] mCurrentPosition = new float[2];

    private void postShopCar(final Goods.ListBean dataBean, final View view) {

        HttpManager.instance()
                .addShopCar(dataBean.getId(), dataBean.getGuid(), dataBean.getCostprice())
                .subscribe(new ErrorHandleSubscriber<GuidBean>() {
                    @Override
                    public void onNext(@NonNull GuidBean s) {
                        updateShowCar(view);
                    }
                });
    }

    private void updateShowCar(View view) {
        shopCarNum = shopCarNum + 1;
        addShopCarAnimation(view, shopCarNum);
    }

    private void queryBefore() {
        String queryContent = et_query.getText().toString().trim();
        if (TextUtils.isEmpty(queryContent)) {
            refresh();
            return;
        }
        mCurrentPage = PAGE_CONTENT_INIT;
        getDataForService(mCurrentPage, queryContent);

    }

    @OnClick({R.id.btn_query, R.id.tv_category, iv_shop_car,})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.iv_shop_car:
                if (shopCarNum == 0) {
                    TsUtils.showToast("请先添加商品");
                } else {
                    Intent intent2 = new Intent(this, ListShopCarActivity.class);
                    startActivity(intent2);
                }
                break;
            case R.id.tv_category:
                mPopCategory.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.btn_query:
                queryBefore();
                break;
            default:
                break;
        }
    }

}
